from pydantic import BaseModel, validator, Field
from typing import Optional
from datetime import datetime

class ProxyBase(BaseModel):
    """代理基础Schema"""
    name: str
    type: str  # 'socks5', 'http', 'https', 'vmess', 'vless', 'trojan'
    host: str
    port: int
    username: Optional[str] = None
    password: Optional[str] = None
    v2ray_config: Optional[str] = None  # v2ray配置JSON字符串
    
    @validator('type')
    def validate_type(cls, v):
        allowed_types = ['socks5', 'http', 'https', 'vmess', 'vless', 'trojan']
        if v not in allowed_types:
            raise ValueError(f'代理类型必须是以下之一: {", ".join(allowed_types)}')
        return v
    
    @validator('port')
    def validate_port(cls, v):
        if not 1 <= v <= 65535:
            raise ValueError('端口号必须在 1-65535 之间')
        return v

class ProxyCreate(ProxyBase):
    """创建代理Schema"""
    pass

class ProxyCreateFromV2Ray(BaseModel):
    """从V2Ray链接创建代理Schema"""
    v2ray_link: str = Field(..., description="V2Ray协议链接 (vmess://, vless://, trojan://)")

class ProxyUpdate(BaseModel):
    """更新代理Schema"""
    name: Optional[str] = None
    type: Optional[str] = None
    host: Optional[str] = None
    port: Optional[int] = None
    username: Optional[str] = None
    password: Optional[str] = None
    v2ray_config: Optional[str] = None
    is_active: Optional[bool] = None
    
    @validator('type')
    def validate_type(cls, v):
        if v is not None:
            allowed_types = ['socks5', 'http', 'https', 'vmess', 'vless', 'trojan']
            if v not in allowed_types:
                raise ValueError(f'代理类型必须是以下之一: {", ".join(allowed_types)}')
        return v
    
    @validator('port')
    def validate_port(cls, v):
        if v is not None and not 1 <= v <= 65535:
            raise ValueError('端口号必须在 1-65535 之间')
        return v

class ProxyResponse(ProxyBase):
    """代理响应Schema"""
    id: int
    user_id: int
    latency: Optional[int] = None
    is_active: bool
    is_shared: bool
    last_test_time: Optional[datetime] = None
    created_at: datetime
    config_link: Optional[str] = None  # 配置链接（仅V2Ray类型代理）
    
    class Config:
        from_attributes = True